<template>
	<div v-loading="is_loading">
		<span class="position-result">{{position_text}}</span>
		<el-button type="primary" @click="get_pos">获取位置</el-button>
	</div>
</template>

<script>
import Vue from 'vue';
import VueAMap from 'vue-amap';

Vue.use(VueAMap);
VueAMap.initAMapApiLoader({
  key: 'f2af30e958d41090138caf8058f73475',
  plugin: ['AMap.Geolocation'],
  // 默认高德 sdk 版本为 1.4.4
  v: '1.4.4'
});

export default {
	data() {
		return {
			is_loading: false,
			position_text: ""
		}
	},
	methods: {
		get_pos() {
			this.is_loading = true
			AMap.plugin('AMap.Geolocation', () => {
				var geolocation = new AMap.Geolocation({
					// 是否使用高精度定位，默认：true
					enableHighAccuracy: true,
					// 设置定位超时时间，默认：无穷大
					timeout: 10000,
					// 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
					buttonOffset: new AMap.Pixel(10, 20),
					//  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
					zoomToAccuracy: true,     
					//  定位按钮的排放位置,  RB表示右下
					buttonPosition: 'RB'
				})

				const onFinal = () => {
					this.is_loading = false
				}

				const onComplete = (data) => {
					console.log(data)
					this.position_text = data.formattedAddress
					this.$emit('answerChange',data)
					onFinal()
				}

				const onError = (data) => {
					console.log(data)
					this.$notify({
						title: 'Could not reach the API.',
						message: data.message
					})
					onFinal()
				}

				geolocation.getCurrentPosition()
				AMap.event.addListener(geolocation, 'complete', onComplete)
				AMap.event.addListener(geolocation, 'error', onError)

			})
		}
	}
}
</script>

<style scoped lang="sass">
.position-result
  padding-left: 1cm
  padding-right: 1cm
</style>
